package ch18.v3.util;

import ch18.v3.model.Student;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {

    private static final String STUDENT_FILE = "students.json"; // 学生数据文件
    private static final Gson GSON = new Gson(); // JSON 工具



    public static List<Student> loadStudents() {
        try (Reader reader = new FileReader(STUDENT_FILE)) {
            Type listType = new TypeToken<List<Student>>() {}.getType();
            return GSON.fromJson(reader, listType);
        } catch (FileNotFoundException e) {
            // 文件不存在，返回一个空列表
            return new ArrayList<>();
        } catch (IOException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    public static void saveStudents(List<Student> students) {
        if (students == null) {
            students = new ArrayList<>();
        }
        try (Writer writer = new FileWriter(STUDENT_FILE)) {
            GSON.toJson(students, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 保存学生数据到文件
    /*public static void saveStudents(List<Student> students) {
        try (Writer writer = new FileWriter(STUDENT_FILE)) {
            GSON.toJson(students, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 从文件读取学生数据
    public static List<Student> loadStudents() {
        try (Reader reader = new FileReader(STUDENT_FILE)) {
            Type listType = new TypeToken<List<Student>>() {}.getType();
            return GSON.fromJson(reader, listType);
        } catch (FileNotFoundException e) {
            return new ArrayList<>(); // 文件不存在返回空列表
        } catch (IOException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }*/

}